package com.hub.grpc.client.service;


import com.hub.grpc.client.config.ExtendResponseObserver;
import com.hub.grpc.proto.ChatRequest;
import com.hub.grpc.proto.ChatResponse;
import com.hub.grpc.proto.ChatServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @ author 飞天蝙蝠
 * @ date & time 2024/12/31 8:54
 */
@Slf4j
@Service
public class ChatClientService {

    private final ChatServiceGrpc.ChatServiceStub chatServiceStub;

    public ChatClientService(ManagedChannel channel) {
        chatServiceStub = ChatServiceGrpc.newStub(channel);
    }

    public String chat(String msg, int user, int count) {
        ExtendResponseObserver<ChatResponse> chatResponseStreamObserver = new ExtendResponseObserver<ChatResponse>() {
            @Override
            public String getExtra() {
                return stringBuilder.toString();
            }
            // 用stringBuilder保存所有来自服务端的响应
            private StringBuilder stringBuilder = new StringBuilder();
            @Override
            public void onNext(ChatResponse chatResponse) {
                log.info("[ChatClientService] onNext.....");
                // 放入匿名类的成员变量中
                System.out.println(chatResponse.getMsg());
                stringBuilder.append(String.format("服务端响应:%s<br>, 用户:%d" , chatResponse.getMsg(), chatResponse.getUserId()));
            }
            @Override
            public void onError(Throwable throwable) {
                log.error("[ChatClientService] gRPC request error");
                stringBuilder.append("[ChatClientService]chat gRPC error, " + throwable.getMessage());
            }
            @Override
            public void onCompleted() {
                log.info("[ChatClientService] onCompleted");
            }
        };
        // 重点！！！！ RPC调用发起
        StreamObserver<ChatRequest> chatRequestStreamObserver = chatServiceStub.chat(chatResponseStreamObserver);
        for(int i = 0; i < count; i++) {
            // 每次执行onNext都会发送一笔数据到服务端，
            // 服务端的onNext方法都会被执行一次
            ChatRequest chatRequest = ChatRequest.newBuilder()
                    .setUserId(user)
                    .setMsg("这是一条来自客户端的消息: 你好，" + user + new SimpleDateFormat("yyyy-MM-dd HH:mm:ssSSS").format(new Date()))
                    .buildPartial();
            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
            chatRequestStreamObserver.onNext(chatRequest);
        }
        // 客户端告诉服务端：数据已经发完了
        chatRequestStreamObserver.onCompleted();
        log.info("service finish");
        return chatResponseStreamObserver.getExtra();
    }
}
